package com.my.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/3/5 14:40
 */

/**
 * 非公平锁：效率高，线程不用频繁切换，但是其它线程可能拿不到资源
 * 公平锁：效率低，线程频繁切换。
 */

class LTicket{
    private int number = 1000;
    private int count = 0;
    
    // 创建可重入锁
    private final ReentrantLock lock = new ReentrantLock();
    
    public void sale(){
        // 上锁
        lock.lock();
        // 判断是否有票可卖
        try {
            if (number > 0){
                System.out.println(Thread.currentThread().getName() + ":卖出了第"
                        + (++count) + "张票剩下" + (--number) + "张票" );
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            // 解锁
            lock.unlock();
        }
    }
}

public class LSaleTicket {

    public static void main(String[] args) {
        LTicket ticket = new LTicket();
        
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    ticket.sale();
                }
            }
        },"AA").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    ticket.sale();
                }
            }
        },"BB").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    ticket.sale();
                }
            }
        },"CC").start();
        
    }
    
}
